package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.base.Jqgrid;
import com.mrd.exception.QueryException;
import com.mrd.framework.security.config.SecurityConstants;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.SpringUtils;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.business.entity.UserService;
import com.mrd.gtimpframe.entity.Company;
import com.mrd.gtimpframe.entity.DeclaCheckTracking;
import com.mrd.gtimpframe.entity.Declaration;
import com.mrd.gtimpframe.entity.User;
import com.mrd.gtimpframe.repository.CompanyMapper;
import com.mrd.gtimpframe.repository.UserMapper;
import com.mrd.gtimpframe.repository.UserServiceMapper;
import com.mrd.gtimpframe.service.DeclarationService;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.LoginUtil;
import com.mrd.util.endecrypt.MD5Util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by lenovo on 2017/7/7.
 */
@Service
public class UserServiceBiz extends BaseBiz<UserService> {
    @Resource
    private DeclarationService declarationService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserServiceMapper userServiceMapper;
    @Resource
    private CompanyMapper companyMapper;

    @Override
    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("userServiceDao")
    public void setBaseRepository(BaseRepository<UserService, String> baseRepository) {
        this.baseRepository = baseRepository;
    }

    /**
     * 判断微信账号是否已经绑定一线通账号
     *
     * @param openid 微信openid
     * @return 绑定结果，0：未绑定；1：已绑定
     */
    public int has_binded(String openid) {
        String sql = "select * from t_gen_user_service t where t.device_code=:openid and t.server_type=:server_type and t.status=:status";
        Map<String, Object> parameters = new HashedMap();
        parameters.put("openid", openid);
        parameters.put("server_type", "WeChat");
        parameters.put("status", "1");
        try {
            int count = this.findEntityCountBySql(sql, parameters);
            return (count > 0 ? 1 : 0);
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return 0;
    }


    public List<UserService> findBindedByOpenid(String openid) {
        String hql = "select UserService from com.mrd.gtimp.business.entity.UserService UserService where UserService.deviceCode='" + openid + "' and UserService.serverType='WeChat' and UserService.status='1'";
        List<UserService> list = this.findEntityByHql(hql, 0, 0, null);
        return list;
    }

    public List<Object> businessStatistics(String companyId, String dateStr) {
        if (StringUtils.isEmpty(companyId) || StringUtils.isEmpty(dateStr)) {
            return null;
        }


        String sql = " select a.tt,sum(已付款),sum(未付款),sum(驳回) from (" +
                " select to_char(b.confirm_time,'yyyymmdd') as tt,count(1) 已付款,0 未付款,0 驳回 from t_biz_base_business b,t_biz_declaration d where b.id=d.id" +
                " and to_date(to_char(b.confirm_time,'yyyymm'),'yyyymm') = to_date(:dateStr,'yyyymm')" +
                " and b.sup_id=:companyId" +
                " and d.payment_type='1'" +
                " group by to_char(b.confirm_time,'yyyymmdd')" +
                " union all" +
                " select to_char(b.confirm_time,'yyyymmdd') as tt,0 已付款,count(1) 未付款,0 驳回 from t_biz_base_business b,t_biz_declaration d where b.id=d.id" +
                " and to_date(to_char(b.confirm_time,'yyyymm'),'yyyymm') = to_date(:dateStr,'yyyymm')" +
                " and b.sup_id=:companyId" +
                " and d.payment_type='0'" +
                " group by to_char(b.confirm_time,'yyyymmdd')" +
                " union all" +
                " select to_char(b.confirm_time,'yyyymmdd') as tt,0 已付款,0 未付款,count(1) 驳回 from t_biz_base_business b,t_biz_declaration d where b.id=d.id" +
                " and to_date(to_char(b.confirm_time,'yyyymm'),'yyyymm') = to_date(:dateStr,'yyyymm')" +
                " and b.sup_id=:companyId" +
                " and d.state='DS03'" +
                " group by to_char(b.confirm_time,'yyyymmdd')" +
                " ) a" +
                " group by a.tt" +
                " order by a.tt";
        Map<String, Object> parameters = new HashedMap();
        parameters.put("companyId", companyId);
        parameters.put("dateStr", dateStr);
        try {
            return this.findObjectBySql(sql, 0, 100, parameters);
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 每月业务数量查询
     *
     * @param date 时间格式yyyymm
     */
    public Map<String, Object> monthDeclaList(String date) {
        Map<String, Object> result = new HashMap<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sdf.parse(date));
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(calendar.getTime());
            calendar2.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
            User user = LoginUtil.getNewLoginUser();
            Map<String, Map<String, Object>> contentMap = new HashMap<>();
            if (user != null && user.getCompany() != null) {
                Map<String, String> propertyMap = new HashMap<>();
                propertyMap.put("ctime", "");
                propertyMap.put("state", "");
                propertyMap.put("id", "");
                Jqgrid jqgrid = new Jqgrid();
                jqgrid.addRule(new SearchRule("CTIME", SearchRuleOption.gt, sdf2.format(calendar.getTime())));
                jqgrid.addRule(new SearchRule("CTIME", SearchRuleOption.lt, sdf2.format(calendar2.getTime())));
                jqgrid.addRule(new SearchRule("CUSTOMER_COM_ID", SearchRuleOption.eq, user.getCompany().getComId()));
                propertyMap.put("whereCase", jqgrid.getWhereCase());
                List<Declaration> declarationList = declarationService.selectByWhereCaseIncludeCheckTracking(propertyMap);
                if (CollectionUtils.isNotEmpty(declarationList)) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
                    SimpleDateFormat strMm = new SimpleDateFormat("MM");
                    for (Declaration declaration : declarationList) {
                        Date createTime = declaration.getCtime();
                        String _createTime = simpleDateFormat.format(createTime);
                        boolean checkReject;
                        long count;
                        Map<String, Object> tempMap = contentMap.get(_createTime);
                        if (MapUtils.isNotEmpty(tempMap)) {
                            checkReject = (boolean) tempMap.get("check_reject");
                            count = (long) tempMap.get("count") + 1;
                        } else {
                            tempMap = new HashMap<>();
                            checkReject = false;
                            count = 1;
                        }
                        if (!checkReject) {
                            List<DeclaCheckTracking> declaCheckTrackingList = declaration.getDeclaCheckTrackingList();
                            if (("DS03".equalsIgnoreCase(declaration.getState()) || (CollectionUtils.isNotEmpty(declaCheckTrackingList) && declaCheckTrackingList.size() > 0))) {
                                checkReject = true;
                            }
                        }
                        tempMap.put("check_reject", checkReject);
                        tempMap.put("count", count);
                        tempMap.put("month", strMm.format(createTime));
                        contentMap.put(_createTime, tempMap);

                    }
                }
                result.put("error", "0");
                result.put("month", date.substring(4, 6));
                result.put("content", contentMap);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.put("error", "1");
        result.put("content", "");
        return result;
    }

    /**
     * 将新绑定的信息 同步更新红包系统
     * @param account 一线通登录账号
     * @param openid 微信openid
     */
    public void insertOrUpdateHongbaoPlatformAccount(String account, String openid){
        String parentId = "82bceb81bf6b4130b65184e05bb43c3d";
        String updateSql = "update VBIZ4_BIZ_DATA t set t.DATAVALUE = ?, t.REGDATE = sysdate where t.DATAKEY = ? and t.DATAKEY IS NOT NULL and t.parentid = ?";
        JdbcTemplate jdbcTemplate = SpringUtils.getBean("hongbaoJdbcTemplate" , JdbcTemplate.class);
        int updateCount = jdbcTemplate.update(updateSql, new Object[]{openid, account, parentId});
        //等于0说明没有可以更新的记录，这时需要新增一条记录
        if(updateCount == 0){
            String insertSql = "insert into VBIZ4_BIZ_DATA(ID, DATAKEY, DATAVALUE,PARENTID,PARENT_ID, REGDATE, BOOLEANVALUE) VALUES(sys_guid(), ?, ?, ?, ?, sysdate, 0)";
            updateCount = jdbcTemplate.update(insertSql, new Object[]{account, openid, parentId, parentId});
        }
        if(updateCount == 0){
            throw new RuntimeException("未能将绑定信息同步到红包系统");
        }
    }

    /**
     * 微信绑定
     *
     * @param account 用户名
     * @param pwd     密码
     * @return {"msg":"提示信息","result":"绑定结果，0：绑定失败；1：绑定成功"}
     */

    @Transactional
    public Map<String, Object> bind_account(String account, String pwd) {
        Map<String, Object> result = new HashMap<>();
        User user = userMapper.selectByAccount(account);
        if (user == null) {
            result.put("msg", "不存在此用户！");
            result.put("result", 0);
            return result;
        }
        String state = user.getuState();
        String isable = user.getuIsabled();
        if (StringUtils.isEmpty(state) || !state.equalsIgnoreCase("0")
                || StringUtils.isEmpty(isable) || !isable.equalsIgnoreCase("0")) {
            result.put("msg", "该用户状态不能绑定！");
            result.put("result", 0);
            return result;
        }
        String pwd4MD5 = user.getuPwd();
        if (!pwd4MD5.equals(MD5Util.string2MD5(pwd))) {
            result.put("msg", "密码不正确！");
            result.put("result", 0);
            return result;
        }
        HttpSession httpSession = HttpUtils.getSession();
        Object sessionOpenid = httpSession.getAttribute(SecurityConstants.WE_CHAT_OPEN_ID);
        if (sessionOpenid == null) {
            result.put("msg", "微信信息获取失败！");
            result.put("result", 0);
            return result;
        }
        com.mrd.gtimpframe.entity.UserService userService = new com.mrd.gtimpframe.entity.UserService();
        userService.setUserId(user.getuId());
        userService.setServerType("WeChat");
        userService.setStatus("1");
        List<com.mrd.gtimpframe.entity.UserService> userServiceList = userServiceMapper.selectSelective(userService);
        if (userServiceList != null && userServiceList.size() > 0) {
            result.put("msg", "该账号已经绑定过了，不能再绑定！");
            result.put("result", 0);
        } else {
            userService = userServiceMapper.selectByWeChatOpenid(sessionOpenid.toString());
            if (userService != null) {
                userService.setModifyTime(new Date());
                userService.setModifier(user.getuName());
                userService.setServerType("WeChat");
                userService.setDeviceCode(sessionOpenid.toString());
                userService.setUserId(user.getuId());
                userService.setStatus("1");
                userServiceMapper.updateByPrimaryKeySelective(userService);
            } else {
                userService = new com.mrd.gtimpframe.entity.UserService();
                userService.setId(UUID.randomUUID().toString());
                userService.setCreateTime(new Date());
                userService.setServerType("WeChat");
                userService.setDeviceCode(sessionOpenid.toString());
                userService.setUserId(user.getuId());
                userService.setStatus("1");
                userServiceMapper.insert(userService);
            }
            Company company = companyMapper.selectByUserId(user.getuId());
            user.setCompany(company);
            httpSession.setAttribute(SecurityConstants.SESSION_USER_NAME, user);
            httpSession.setAttribute(SecurityConstants.NEW_SESSION_USER_NAME, user);
            result.put("msg", "绑定成功！");
            result.put("result", 1);
            //为了可以发送红包，需要将绑定资料同步到红包系统的数据表中
            insertOrUpdateHongbaoPlatformAccount(user.getuAccount(), sessionOpenid + "");
        }
        return result;
    }
}
